# -*- coding: utf-8 -*-
"""
Precipitation HDF4 data read and calculate.


Created on Mon Apr  1 11:33:21 2019

@author: Farman-X220
"""

import os
import pyhdf.SD as hdf


def hdf_info_str(file_name):
    '''
    Fetch hdf arrtibutes and return as string.
    
    Parameters
    ----------
    file_name : string.
        Name of HDF4 file to fetch attributes.

    Returns
    -------
    Multi-line string of HDF file attributes.

    '''
    attr_str = ""  + '\n'
    
    attr_str += '\n\nFILE : %s\n'%os.path.abspath(file_name) + '\n'
    hdf_obj = hdf.SD(file_name)
    
    #--------------------------------------------------------
    
    attr_str += '*** HDF ATTRIBUTES ***'  + '\n'
    attr_str += '='*40 + '\n'
    attributes = hdf_obj.attributes()
    
    for k in attributes:
        attr_str += '\n'
        attr_str += k  + '\n'
        attr_str += '-' * 20  + '\n'
        attr_str += attributes.get(k)  + '\n'
    
    #--------------------------------------------------------
    
    attr_str += '*** HDF DATASETS ***' + '\n'
    attr_str += '=' * 40 + '\n'
    attr_str += '\n'
    attr_str += 'Index DatasetName' + '\n'
    attr_str += '-' * 20 + '\n'
    
    data_dic = hdf_obj.datasets()
    
    for k in data_dic.keys():
        attr_str += str(hdf_obj.nametoindex(k)) + ' '*3 + k + '\n'
    
    hdf_obj.end()
    return attr_str

hdf_file = 'MOD13Q1.A2015353.h00v08.006.2016007175958.hdf'
s = hdf_info_str(hdf_file)

with open('attr.txt', 'w') as f:
    f.write(s)



def hdf_info(file_name):
    '''
    Show info of HDF4 file given.
    '''
    print('\n\nFILE : %s\n'%os.path.abspath(file_name))
    hdf_obj = hdf.SD(file_name)
    
    #--------------------------------------------------------
    
    print('*** HDF ATTRIBUTES ***')
    print('='*40, '\n')
    attributes = hdf_obj.attributes()
    
    for k in attributes:
        print(k)
        print('-' * 20)
        print(attributes.get(k))
    
    #--------------------------------------------------------
    
    print('*** HDF DATASETS ***')
    print('=' * 40)
    print('Index DatasetName')
    print('-' * 20)
    
    data_dic = hdf_obj.datasets()
    
    for k in data_dic.keys():
        print(hdf_obj.nametoindex(k), ' '*3, k)
    
    hdf_obj.end()
    return


'''
file_name = r"Data\3B43.20000101.7A.HDF"
hdf_info(file_name)
#'''


def read_hdf(file_name, dataset_name):
    '''
    Read month precipitation data from HDF4 file.
    '''
    hdf_obj = hdf.SD(file_name)
    data = hdf_obj.select(dataset_name).get()
    hdf_obj.end()
    return data

'''
file_name = r"Data\3B43.20000101.7A.HDF"
d = read_month_precipitation(file_name)
#'''   


def save_hdf(data, dataset_name, file_name):
    '''
    Save data to HDF4 file with name 'file_name'.
    '''
    hdf_obj = hdf.SD(file_name, hdf.SDC.CREATE | hdf.SDC.WRITE)
    
    trans_tab = {# for proper functionality, unsigned type must appear first.
            'uchar':hdf.SDC.UCHAR,
            'uchar8':hdf.SDC.UCHAR8,
            'char':hdf.SDC.CHAR,
            'char8':hdf.SDC.CHAR8,            
            'uint8':hdf.SDC.UINT8,
            'uint16':hdf.SDC.UINT16,
            'unit32':hdf.SDC.UINT32,
            'int8':hdf.SDC.INT8,
            'int16':hdf.SDC.INT16,
            'int32':hdf.SDC.INT32,
            'float32':hdf.SDC.FLOAT32,
            'float64':hdf.SDC.FLOAT64,}
    
    dtype = trans_tab.get(data.dtype.name)    
    hdf_obj.create(dataset_name, dtype, data.shape)
    dataset = hdf_obj.select(dataset_name)
    dataset.set(data)
    hdf_obj.end()
    
    print('Saved :', file_name)
    return

'''
file_name = 'a.hdf'
d = calc_annual_precipitation('Data')
save_hdf(d, file_name)
hdf_info(file_name)
#'''

if __name__ == '__main__':
    print('''
*****************************************************
*                                                   *
*             HDF4   DATA   MANIPULATION            *
*                                                   *
*                          Farman @ 2019-04-02 Mon. *
*                              Ailsasoft Inc., Ltd. *
*                                                   *
*****************************************************
          ''')
    